package com.example.milimili;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompatSideChannelService;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.milimili.bean.NewsInfo;
import com.example.milimili.util.DateUtil;
import com.example.milimili.util.WebChecker;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class SearchActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener,
        SwipeRefreshAndMoreLoadLayout.OnLoadMoreListener {
    private final String firstPathPart="https://api2.newsminer.net/svc/news/queryNewsList?size=50&startDate=";
    private final String secondPathPart="&endDate=";
    private final String thirdPathPart="&words=";
    private final String fourthPathPart="&categories=";
    public static String startDate,endDate,category;

    ImageButton backBtn,searchBtn,searchConstraintBtn;
    EditText searchText;
    ListView newsList;
    TextView newsText,chubanText,dateText;
    ImageView myImage;

    public static String keyWord;
    private String path;
    private String json;
    List<HashMap<String, Object>> jsonMap = new ArrayList<>();
    private List<Boolean> videoCheck=new ArrayList<>();
    private List<Boolean> noImageCheck=new ArrayList<>();
    private MyAdapter myAdapter=new MyAdapter();
    private SwipeRefreshAndMoreLoadLayout mRefreshLayout;
    private int sizecount=20;
    private int pageNum=1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        Intent intent=this.getIntent();
        keyWord=intent.getStringExtra("keyWord");
        keyWord=keyWord.trim();
//        path=MainActivity.FIRSTPART+ DateUtil.getNowDateTime()+MainActivity.SECONDPART+keyWord+MainActivity.THIRDPART;
        path=firstPathPart+startDate+secondPathPart+endDate+thirdPathPart+keyWord+fourthPathPart+category;
        startDate="2021-08-20";
        endDate=DateUtil.getNowDateTime();
        SearchActivity.category="";
//        Log.e("search",path);
        initView();
        newsList=findViewById(R.id.list);
        mRefreshLayout = (SwipeRefreshAndMoreLoadLayout) SearchActivity.this.findViewById(R.id.refresh);
        mRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        mRefreshLayout.setOnRefreshListener(SearchActivity.this);
        mRefreshLayout.setOnLoadMoreListener(SearchActivity.this);
        mRefreshLayout.setAdapte(newsList, myAdapter);
        webThread.start();
        try {
            webThread.join();
//            Log.e("search",json);
            getJson();
            newsList=findViewById(R.id.list);
            newsList.setAdapter(myAdapter);
            newsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    if(videoCheck.get(i))
                    {
                        Intent intent=new Intent(view.getContext(),VedioNewsActivity.class);
                        final SerializableMap myMap=new SerializableMap();
                        myMap.setMap(jsonMap.get(i));//将map数据添加到封装的myMap中
                        myMap.setPosition(i);
                        myMap.setPath(path);
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("map", myMap);
                        intent.putExtras(bundle);
                        MySQLiteOpenHelper mySQLiteOpenHelper=new MySQLiteOpenHelper(SearchActivity.this);
                        NewsInfo newsInfo = new NewsInfo();
                        newsInfo.setTitle(jsonMap.get(i).get("title").toString());
                        newsInfo.setImage(jsonMap.get(i).get("image").toString());
                        newsInfo.setPath(path);
                        newsInfo.setPosition(i);
                        newsInfo.setContent(jsonMap.get(i).get("content").toString());
                        long rowId = mySQLiteOpenHelper.insertData(2,newsInfo);
//                        Log.e("gray","变灰");
                        myAdapter.notifyDataSetChanged();
                        startActivity(intent);
                    }
                    else if(noImageCheck.get(i))
                    {
                        NewsActivity.flag=false;
                        Intent intent=new Intent(view.getContext(),NoImageNewsActivity.class);
                        final SerializableMap myMap=new SerializableMap();
                        myMap.setMap(jsonMap.get(i));//将map数据添加到封装的myMap中
                        myMap.setPath(path);
                        myMap.setPosition(i);
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("map", myMap);
                        intent.putExtras(bundle);
                        MySQLiteOpenHelper mySQLiteOpenHelper=new MySQLiteOpenHelper(SearchActivity.this);
                        NewsInfo newsInfo = new NewsInfo();
                        newsInfo.setTitle(jsonMap.get(i).get("title").toString());
                        newsInfo.setImage(jsonMap.get(i).get("image").toString());
                        newsInfo.setPath(path);
//                        Log.e("col",newsInfo.getPath());
                        newsInfo.setPosition(i);
                        newsInfo.setContent(jsonMap.get(i).get("content").toString());
                        long rowId = mySQLiteOpenHelper.insertData(2,newsInfo);
//                        Log.e("gray","变灰");
                        myAdapter.notifyDataSetChanged();
                        startActivity(intent);
                    }
                    else
                    {
//                        Log.e("点击：",jsonMap.get(i).get("title").toString());
                        NewsActivity.flag=false;
                        Intent intent=new Intent(view.getContext(),NewsActivity.class);
                        final SerializableMap myMap=new SerializableMap();
                        myMap.setMap(jsonMap.get(i));//将map数据添加到封装的myMap中
                        myMap.setPath(path);
                        myMap.setPosition(i);
                        Bundle bundle=new Bundle();
                        bundle.putSerializable("map", myMap);
                        intent.putExtras(bundle);
                        MySQLiteOpenHelper mySQLiteOpenHelper=new MySQLiteOpenHelper(SearchActivity.this);
                        NewsInfo newsInfo = new NewsInfo();
                        newsInfo.setTitle(jsonMap.get(i).get("title").toString());
                        newsInfo.setImage(jsonMap.get(i).get("image").toString());
                        newsInfo.setPath(path);
//                        Log.e("col",newsInfo.getPath());
                        newsInfo.setPosition(i);
                        newsInfo.setContent(jsonMap.get(i).get("content").toString());
                        long rowId = mySQLiteOpenHelper.insertData(2,newsInfo);
//                        Log.e("gray","变灰");
                        myAdapter.notifyDataSetChanged();
                        startActivity(intent);
                    }
                }
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        backBtn=findViewById(R.id.back);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Intent intent=new Intent(SearchActivity.this,MainActivity.class);
//                SearchActivity.this.startActivity(intent);
                SearchActivity.this.finish();
            }
        });
        searchBtn=findViewById(R.id.search);
        searchText=findViewById(R.id.searchText);
        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(WebChecker.isConnectIsNormal(SearchActivity.this))
                {
                    Intent intent=new Intent(SearchActivity.this,SearchActivity.class);
//                    Log.e("check",searchText.getText().toString());
                    intent.putExtra("keyWord",searchText.getText().toString());
                    SearchActivity.this.startActivity(intent);
                }
                else
                {
                    Intent intent=new Intent(SearchActivity.this,NoWebEmptyActivity.class);
                    SearchActivity.this.startActivity(intent);
                }
            }
        });
    }

    Thread webThread = new Thread(new Runnable() {
        @Override
        public void run() {
            getWeb();
        }
    });

    private void getWeb() {
        try {
            json = HtmlService.getHtml(path);
//            System.out.println(json.length());
//            Log.e(TAG, "html : " + json);
//            System.out.println(html);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getJson() {
        try {
//            Log.e(TAG,json);
            JSONObject rootObject=new JSONObject(json);
            JSONArray dataArray=rootObject.getJSONArray("data");
            for(int i=0;i<dataArray.length();i++)
            {
                JSONObject newsObject = dataArray.getJSONObject(i);
                String imageAll=newsObject.getString("image");
                String imageTmp1=imageAll.substring(1,imageAll.length()-1);
                String imageTmp=imageTmp1.replace("] [",", ");
                String video= newsObject.getString("video");
                String title= newsObject.getString("title");
                String content=newsObject.getString("content");
                String organizations= newsObject.getString("organizations");
                String publisher=newsObject.getString("publisher");
                String time=newsObject.getString("publishTime");
//                Log.e(TAG,title);
                HashMap<String, Object> map = new HashMap<>();
                map.put("image",imageTmp);
                map.put("video", video);
                map.put("title", title);
                map.put("content",content);
                map.put("organization", video);
                map.put("publisher",publisher);
                map.put("publishTime",time);
                jsonMap.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                if(WebChecker.isConnectIsNormal(SearchActivity.this))
                {
                    mRefreshLayout = (SwipeRefreshAndMoreLoadLayout) SearchActivity.this.findViewById(R.id.refresh);
                    mRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,
                            android.R.color.holo_green_light,
                            android.R.color.holo_orange_light,
                            android.R.color.holo_red_light);
                    mRefreshLayout.setOnRefreshListener(SearchActivity.this);
                    mRefreshLayout.setOnLoadMoreListener(SearchActivity.this);
                    mRefreshLayout.setAdapte(newsList, myAdapter);
                    Thread webThread=new Thread(new Runnable() {
                        @Override
                        public void run() {
                            getWeb();
                        }
                    });
                    path=firstPathPart+startDate+secondPathPart+endDate+thirdPathPart+keyWord+fourthPathPart+category;
                    webThread.start();
                    try {
                        webThread.join();
                        jsonMap.clear();
                        Log.e("listClear:","列表被清空");
                        Log.e("listClear:",String.valueOf(jsonMap.size()));
                        getJson();
//                MyAdapter myAdapter=new MyAdapter();
                        newsList.setAdapter(myAdapter);
                        newsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                if(videoCheck.get(i))
                                {
                                    Intent intent=new Intent(view.getContext(),VedioNewsActivity.class);
                                    final SerializableMap myMap=new SerializableMap();
                                    myMap.setMap(jsonMap.get(i));//将map数据添加到封装的myMap中
                                    myMap.setPosition(i);
                                    myMap.setPath(path);
                                    Bundle bundle=new Bundle();
                                    bundle.putSerializable("map", myMap);
                                    intent.putExtras(bundle);
                                    MySQLiteOpenHelper mySQLiteOpenHelper=new MySQLiteOpenHelper(SearchActivity.this);
                                    NewsInfo newsInfo = new NewsInfo();
                                    newsInfo.setTitle(jsonMap.get(i).get("title").toString());
                                    newsInfo.setImage(jsonMap.get(i).get("image").toString());
                                    newsInfo.setPath(path);
                                    newsInfo.setPosition(i);
                                    newsInfo.setContent(jsonMap.get(i).get("content").toString());
                                    long rowId = mySQLiteOpenHelper.insertData(2,newsInfo);
//                                    Log.e("gray","变灰");
                                    myAdapter.notifyDataSetChanged();
                                    startActivity(intent);
                                }
                                else {
                                    NewsActivity.flag=false;
//                Log.e("点击：",jsonMap.get(i).get("title").toString());
                                    Intent intent=new Intent(view.getContext(),NewsActivity.class);
                                    final SerializableMap myMap=new SerializableMap();
                                    myMap.setMap(jsonMap.get(i));//将map数据添加到封装的myMap中
                                    myMap.setPosition(i);
                                    myMap.setPath(path);
                                    Bundle bundle=new Bundle();
                                    bundle.putSerializable("map", myMap);
                                    intent.putExtras(bundle);
                                    MySQLiteOpenHelper mySQLiteOpenHelper=new MySQLiteOpenHelper(SearchActivity.this);
                                    NewsInfo newsInfo = new NewsInfo();
                                    newsInfo.setTitle(jsonMap.get(i).get("title").toString());
                                    newsInfo.setImage(jsonMap.get(i).get("image").toString());
                                    newsInfo.setPath(path);
                                    newsInfo.setPosition(i);
                                    newsInfo.setContent(jsonMap.get(i).get("content").toString());
                                    long rowId = mySQLiteOpenHelper.insertData(2,newsInfo);
//                                    Log.e("gray","变灰");
                                    myAdapter.notifyDataSetChanged();
                                    startActivity(intent);
                                }
                            }
                        });
                        myAdapter.notifyDataSetChanged();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                else
                {
                    ;
                }
                mRefreshLayout.setRefreshing(false);
            }
        }, 2000);
    }

    @Override
    public void onLoadMore() {
        mRefreshLayout.setLoadingContext("正在加载");
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                if(WebChecker.isConnectIsNormal(SearchActivity.this))
                {
                    sizecount=sizecount+20;
                    path=MainActivity.ONEPART+sizecount+MainActivity.TWOPART+DateUtil.getNowDateTime()+MainActivity.SECONDPART+keyWord+MainActivity.THIRDPART+category;
//                    Log.e("搜索加载：",path);
                    Thread webThread=new Thread(new Runnable() {
                        @Override
                        public void run() {
                            getWeb();
                        }
                    });
                    webThread.start();
                    try {
                        webThread.join();
                        jsonMap.clear();
                        getJson();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                else
                {
                    ;
                }
                mRefreshLayout.setLoading(false);
            }
        }, 2000);
    }

    private class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return jsonMap.size();
        }

        @Override
        public Object getItem(int i) {
            return jsonMap.get(i).get("title");
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            String imageAll=jsonMap.get(i).get("image").toString();
//            Log.e("image:",imageAll);
            String[] imageArray=imageAll.split(", ");
            if(imageArray.length>=3&&imageArray[0].length()>=5&&imageArray[1].length()>=5&&imageArray[2].length()>=5)
            {
                noImageCheck.add(false);
                View itemView=View.inflate(SearchActivity.this,R.layout.multi_image_itemlayout,null);
                newsText=itemView.findViewById(R.id.name);
                newsText.setText(jsonMap.get(i).get("title").toString());
                chubanText=itemView.findViewById(R.id.chuban);
                if(jsonMap.get(i).get("publisher")!=null)
                {
                    chubanText.setText(jsonMap.get(i).get("publisher").toString());
                }
                dateText=itemView.findViewById(R.id.date);
                if(jsonMap.get(i).get("publishTime")!=null)
                {
                    dateText.setText(jsonMap.get(i).get("publishTime").toString());
                }
//            if(jsonMap.get(i).get("video").toString().length()!=0)
                if(jsonMap.get(i).get("video").toString().length()!=0)
                {
                    videoCheck.add(true);
                    Log.e("视频：","有一个视频不为空"+"  "+jsonMap.get(i).get("title").toString());
                }
                else
                {
                    videoCheck.add(false);
                }
                ImageView image1,image2,image3;
                image1=itemView.findViewById(R.id.image1);
                image2=itemView.findViewById(R.id.image2);
                image3=itemView.findViewById(R.id.image3);
//                Log.e("image1",imageArray[0]);
//                Log.e("image2",imageArray[1]);
//                Log.e("image3",imageArray[2]);
                Glide.with(SearchActivity.this).load(imageArray[0]).into(image1);
                Glide.with(SearchActivity.this).load(imageArray[1]).into(image2);
                Glide.with(SearchActivity.this).load(imageArray[2]).into(image3);
                MySQLiteOpenHelper mySQLiteOpenHelper=new MySQLiteOpenHelper(SearchActivity.this);
                if(mySQLiteOpenHelper.checkFromDbByTitle(2,jsonMap.get(i).get("title").toString()))
                {
                    ;
                }
                else
                {
                    newsText.setTextColor(Color.parseColor("#7D7D7D"));
                    chubanText.setTextColor(Color.parseColor("#7D7D7D"));
                    dateText.setTextColor(Color.parseColor("#7D7D7D"));
                }
                return itemView;
            }
            else if(imageArray.length==0||imageArray[0].length()<=5)
            {
                noImageCheck.add(true);
                View itemView=View.inflate(SearchActivity.this,R.layout.no_image_itemlayout,null);
                newsText=itemView.findViewById(R.id.name);
                newsText.setText(jsonMap.get(i).get("title").toString());
                chubanText=itemView.findViewById(R.id.chuban);
                if(jsonMap.get(i).get("publisher")!=null)
                {
                    chubanText.setText(jsonMap.get(i).get("publisher").toString());
                }
                dateText=itemView.findViewById(R.id.date);
                if(jsonMap.get(i).get("publishTime")!=null)
                {
                    dateText.setText(jsonMap.get(i).get("publishTime").toString());
                }
//            if(jsonMap.get(i).get("video").toString().length()!=0)
                if(jsonMap.get(i).get("video").toString().length()!=0)
                {
                    videoCheck.add(true);
                    Log.e("视频：","有一个视频不为空"+"  "+jsonMap.get(i).get("title").toString());
                }
                else
                {
                    videoCheck.add(false);
                }
                MySQLiteOpenHelper mySQLiteOpenHelper=new MySQLiteOpenHelper(SearchActivity.this);
                if(mySQLiteOpenHelper.checkFromDbByTitle(2,jsonMap.get(i).get("title").toString()))
                {
                    ;
                }
                else
                {
                    newsText.setTextColor(Color.parseColor("#7D7D7D"));
                    chubanText.setTextColor(Color.parseColor("#7D7D7D"));
                    dateText.setTextColor(Color.parseColor("#7D7D7D"));
                }
                return itemView;
            }
            else
            {
                noImageCheck.add(false);
                View itemView=View.inflate(SearchActivity.this,R.layout.itemlayout,null);
                newsText=itemView.findViewById(R.id.name);
                myImage=itemView.findViewById(R.id.picture);
                newsText.setText(jsonMap.get(i).get("title").toString());
                chubanText=itemView.findViewById(R.id.chuban);
                if(jsonMap.get(i).get("publisher")!=null)
                {
                    chubanText.setText(jsonMap.get(i).get("publisher").toString());
                }
                dateText=itemView.findViewById(R.id.date);
                if(jsonMap.get(i).get("publishTime")!=null)
                {
                    dateText.setText(jsonMap.get(i).get("publishTime").toString());
                }
//            if(jsonMap.get(i).get("video").toString().length()!=0)
                if(jsonMap.get(i).get("video").toString().length()!=0)
                {
                    videoCheck.add(true);
                    Log.e("视频：","有一个视频不为空"+"  "+jsonMap.get(i).get("title").toString());
                }
                else
                {
                    videoCheck.add(false);
                }
                MySQLiteOpenHelper mySQLiteOpenHelper=new MySQLiteOpenHelper(SearchActivity.this);
                if(mySQLiteOpenHelper.checkFromDbByTitle(2,jsonMap.get(i).get("title").toString()))
                {
                    ;
                }
                else
                {
                    newsText.setTextColor(Color.parseColor("#7D7D7D"));
                    chubanText.setTextColor(Color.parseColor("#7D7D7D"));
                    dateText.setTextColor(Color.parseColor("#7D7D7D"));
                }
                if(imageArray.length!=0)
                {
//                Log.e("imagecheck:",imageArray[0]);
                    Glide.with(SearchActivity.this).load(imageArray[0]).into(myImage);
                }
                return itemView;
            }
//
        }
    }
}